package com.rxnetwork.sample.module.home.adapter

import android.app.Activity
import android.content.Context
import android.support.v7.widget.AppCompatImageView
import android.support.v7.widget.AppCompatTextView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import com.bumptech.glide.Glide
import com.rxnetwork.sample.R
import com.rxnetwork.sample.model.ListModel

class MainAdapter(activity: Activity, listModels: MutableList<ListModel>) : RecyclerView.Adapter<MainAdapter.MainAdapterHolder>() {

    private var mItemClickListener: MyItemClickListener? = null

    private val mContext: Context

    private var listModels: MutableList<ListModel>? = null

    init {
        this.listModels = listModels
        mContext = activity
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapterHolder {
        return MainAdapterHolder(LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false), mItemClickListener)
    }

    override fun onBindViewHolder(holder: MainAdapterHolder, position: Int) {
        if (listModels == null) {
            return
        }
        Glide
                .with(holder.imageView.context)
                .load(listModels!![position].titleImage)
                .placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .centerCrop()
                .into(holder.imageView)
        holder.textView.text = listModels!![position].title
    }

    override fun getItemCount(): Int {
        return listModels?.size ?: 0
    }

    fun addAll(data: List<ListModel>) {
        if (listModels != null) {
            listModels?.addAll(data)
            notifyDataSetChanged()
        }
    }

    fun clear() {
        if (listModels != null) {
            listModels?.clear()
            notifyDataSetChanged()
        }
    }

    inner class MainAdapterHolder(itemView: View, mlistener: MyItemClickListener?) : RecyclerView.ViewHolder(itemView), View.OnClickListener {

        val imageView: AppCompatImageView
        val textView: AppCompatTextView
        var mListener: MyItemClickListener? = null

        init {
            mListener = mlistener
            imageView = itemView.findViewById(R.id.list_image) as AppCompatImageView
            textView = itemView.findViewById(R.id.list_tv) as AppCompatTextView
            itemView.setOnClickListener(this)
        }//将全局的监听赋值给接口

        override fun onClick(view: View) {
            mListener?.onItemClick(view, adapterPosition)
        }
    }

    interface MyItemClickListener {
        fun onItemClick(view: View, position: Int)
    }

    /**
     * 在activity里面adapter就是调用的这个方法,将点击事件监听传递过来,并赋值给全局的监听

     * @param myItemClickListener
     */
    fun setItemClickListener(myItemClickListener: MyItemClickListener) {
        this.mItemClickListener = myItemClickListener
    }

}
